
#include "msg_queue.h"

static msg_queue_t  msg_queue;

int msg_queue_init(void)
{
    msg_queue.len = 0;

    msg_queue.e_head = (slist_t *)psram_malloc(sizeof(slist_t));
	if (msg_queue.e_head == NULL) {
		l_d("e_head null\n");
		return -1;
	}
    slist_init(msg_queue.e_head);
    return 0;
}

int msg_queue_destroy(void)
{
	if(!msg_queue.e_head){
		return -1;
	}


    return 0;
}

int msg_queue_send(msg_notify_t *msg)
{
    msg_link_t * obj = NULL;
	
	if(!msg_queue.e_head){
		return -1;
	}

    obj = (msg_link_t *)psram_malloc(sizeof(msg_link_t));
    if(obj == NULL){
        l_d("obj err\n");
        return -1;
    }
    memset(obj, 0, sizeof(msg_link_t));
    slist_init(&(obj->e_tail));
    //**************************************************
    obj->e_attr.cmd     = msg->cmd;
    obj->e_attr.data0   = msg->data0;
    obj->e_attr.data1   = msg->data1;
	obj->e_attr.data2   = msg->data2;
	obj->e_attr.para    = msg->para;
    //**************************************************
    msg_queue.len++;
    slist_add_tail(msg_queue.e_head,&(obj->e_tail));
    //**************************************************

    return 0;
}

int msg_queue_recv(msg_notify_t * msg)
{
	int ret = 0;
	slist_t* node;
	msg_link_t * obj = NULL;

	if(!msg_queue.e_head){
		return -1;
	}

	if(slist_isempty(msg_queue.e_head)){
		return -1;
	}

    //l_d("len=%d\n",msg_queue.len);

	slist_for_each(node, (msg_queue.e_head))
	{
		obj = slist_entry(node, msg_link_t, e_tail);
		if(obj){
            memcpy(msg,&obj->e_attr,sizeof(msg_notify_t));
            ret = 1;
            break;
		}
	}

	if(ret){
		slist_remove(msg_queue.e_head, &(obj->e_tail));
		msg_queue.len--;

        if(obj){
            psram_free(obj);
            obj = NULL;
        }
	}

	return 0;
}

int msg_queue_trav(void)
{
    int i = 0;
	slist_t* node;
    msg_link_t * obj = NULL;

	if(!msg_queue.e_head){
		return -1;
	}

	if(slist_isempty(msg_queue.e_head)){
		l_d("list empty.\n");
		return -1;
	}

	slist_for_each(node,(msg_queue.e_head))
	{
		obj = slist_entry(node,msg_link_t,e_tail);
		if(obj){
			#if 1
			l_d("i:cmd=%d:%d\n",i,obj->e_attr.cmd);
			#endif
            i++;
		}
	}

	return 0;
}

int msg_queue_get_len(void)
{
    l_d("len=%d\n",msg_queue.len);

    return msg_queue.len;
}

